#include "ota_http.h"

int get_text(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    size_t size_all = size * nmemb;
    memcpy(userdata, ptr, size_all);
    ((char *)userdata)[size_all] = '\0';

    return size_all;
}

/// @brief 获取文本
/// @param url 访问地址
/// @return char* 获取的文本数据
char *ota_http_get_text(char *url)
{
    CURL *curl;

    CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);

    curl = curl_easy_init();
    if (curl == NULL)
    {
        log_error("curl_easy_init() failed");
        curl_global_cleanup();
        return NULL;
    }

    curl_easy_setopt(curl, CURLOPT_URL,url);

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, get_text);

    // 设置回调函数的参数, 用来接收收到的数据
    char *buffer = (char *)malloc(1024);
    memset(buffer, 0, 1024);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, buffer);
    

    res = curl_easy_perform(curl);

    if (res != CURLE_OK)
    {
        log_error("curl_easy_perform() failed: %s", curl_easy_strerror(res));
        curl_easy_cleanup(curl);
        return NULL;
    }

    curl_easy_cleanup(curl);
    return buffer;
}

/// @brief http下载
/// @param url 
/// @param file_path 
/// @return 
Com_state_t ota_http_download(char* url,char *file_path)
{
    CURL *curl;

    //初始化curl
    curl = curl_easy_init();

    if (curl == NULL)
    {
        log_error("curl_easy_init() failed");
        curl_easy_cleanup(curl);
        return Com_FAIL;
    }

    //设置需要访问的url
    curl_easy_setopt(curl,CURLOPT_URL,url);

    //设置回调函数，获取文件数据
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,fwrite);

    FILE *fp = fopen(file_path,"wb");

    if (fp == NULL)
    {
        log_error("fopen() failed");
        curl_easy_cleanup(curl);
        return Com_FAIL;
    }
    
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,fp);

    CURLcode res = curl_easy_perform(curl);

    log_info("curl_easy_perform() res:%d",res);
    if (res != CURLE_OK)
    {
        log_error("curl_easy_perform() failed: %s",curl_easy_strerror(res));
        curl_easy_cleanup(curl);
        fclose(fp);
        return Com_FAIL;
    }
    
    long http_code = 0;
    curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE,&http_code);
    if (http_code != 200)
    {
        log_error("http_code: %ld",http_code);
        curl_easy_cleanup(curl);
        fclose(fp);
        return Com_FAIL;
    }
    
    curl_easy_cleanup(curl);

    fclose(fp);

    return Com_OK;
}

